import global from './global.js'
import user from './user.js'
import {
    testContract
} from '../api/contract'
// 简单确认框提示框
export function confirm(cont, confirmText = '确定', cancelText = '取消', cancelColor = '') {
    return new Promise((reslove, reject) => {
        wx.showModal({
            title: '提示',
            content: cont,
            cancelText,
            confirmText,
            cancelColor,
            success: (res) => {
                if (res.confirm)
                    reslove()
                if (res.cancel)
                    reject()
            },
            fail: () => {
                reject()
            }
        })
    })
}
// 简单提示框，只有确认
export function alert(cont) {
    return new Promise((reslove) => {
        wx.showModal({
            title: '提示',
            content: cont,
            showCancel: false,
            success: () => {
                reslove()
            }
        })
    })
}
// 身份证转年龄
export function getCardAge(identityCard) {
    let len = (identityCard + '').length
    if (len == 0) {
        return 0
    } else {
        if ((len != 15) && (len != 18)) // 身份证号码只能为15位或18位其它不合法
        {
            return 0
        }
    }
    let strBirthday = ''
    if (len == 18) // 处理18位的身份证号码从号码中得到生日和性别代码
    {
        strBirthday = identityCard.substr(6, 4) + '/' + identityCard.substr(10, 2) + '/' + identityCard.substr(12, 2)
    }
    if (len == 15) {
        strBirthday = '19' + identityCard.substr(6, 2) + '/' + identityCard.substr(8, 2) + '/' + identityCard.substr(10, 2)
    }
    // 时间字符串里，必须是“/”
    let birthDate = new Date(strBirthday)
    let nowDateTime = new Date()
    let age = nowDateTime.getFullYear() - birthDate.getFullYear()
    // 再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
    if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {
        age--
    }
    return age

}
// 轻提示
export function toast(cont, type = 'none', duration = 2000) {
    setTimeout(() => {
        wx.showToast({
            icon: type,
            title: cont,
            duration: duration,
        })
    }, 100)
}

/** 判断有没有指定的时间格式 */
export function dateFormat(fmt, date) {
    let ret
    const opt = {
        'Y+': date.getFullYear().toString(), // 年
        'm+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'M+': date.getMinutes().toString(), // 分
        'S+': date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    }
    for (let k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
        }
    }
    return fmt
}

export function urlTobase64(url, ishead = false) {
    return new Promise((reslove) => {
        wx.request({
            url: url,
            responseType: 'arraybuffer', // 最关键的参数，设置返回的数据格式为arraybuffer
            success: res => {
                // 把arraybuffer转成base64
                let base64 = wx.arrayBufferToBase64(res.data)

                // 不加上这串字符，在页面无法显示的哦
                base64 = (ishead ? 'data:image/jpeg;base64,' : '') + base64

                // 打印出base64字符串，可复制到网页校验一下是否是你选择的原图片呢
                reslove(base64)
            }
        })
    })
}

// 本地文件转base64
export function wxfileTobase64(url, ishead = false) {
    return new Promise((reslove, reject) => {
        wx.getFileSystemManager().readFile({
            filePath: url, // 选择图片返回的相对路径
            encoding: 'base64', // 编码格式
            success: res => { // 成功的回调
                reslove((ishead ? 'data:image/jpeg;base64,' : '') + res.data)
            },
            fail: err => {
                reject(err)
            }
        })
    })
}

// base64转本地文件 
export function base64ToWxfile(base64, fileName) {
    const path = wx.env.USER_DATA_PATH + '/' + fileName
    return new Promise((reslove, reject) => {
        wx.getFileSystemManager().writeFile({
            filePath: path,
            data: base64,
            encoding: 'base64',
            success: () => {
                reslove(path)
            },
            fail: (err) => {
                console.log(err)
                reject(err)
            }
        })
    })
}
// 简易双向绑定
export function inputchange(event, t) {
    t.setData({
        [event.currentTarget.dataset.model]: event.detail.value
    })
}

// 防抖
export function shake() {
    let timer = -1
    return function (obj, millisecond = 500) {
        clearTimeout(timer)
        if (obj)
            timer = setTimeout(obj, millisecond)
    }
}
export const anit = shake()

/**
 * @param {String} url, // 应用路径，用于跳转链接
 * @param {['可用','建设中','维护中','下线']} status, // 应用状态，用于提示
 * @param {['navigateTo','redirectTo']} type, // 应用状态，用于提示
 */
export function goApp(url, type = 'navigateTo', status = 0) {
    return new Promise((resolve) => {
        switch (status) {
            case 0:
                // 如果传的url是空的
                if (!url) {
                    toast('应用维护中，请稍后再试')
                    return 0
                }

                // 判断应用类型，不同类型做不同的跳转方法
                if (/^https?:\/\//.test(url)) { // H5应用
                    if (type === 'redirectTo') {
                        wx.redirectTo({
                            url: '/pages/web-view/web-view?path=' + encodeURIComponent(url),
                            success(res) {
                                resolve(res)
                            }
                        })
                    } else {
                        wx.navigateTo({
                            url: '/pages/web-view/web-view?path=' + encodeURIComponent(url),
                            success(res) {
                                resolve(res)
                            }
                        })
                    }
                } else if (/^external:\/\//.test(url)) { // 外部应用   应用格式    external://appId/path
                    url = url.split('external://')[1]
                    const list = url.split('/')
                    const appId = list.splice(0, 1).join()
                    const path = '/' + list.join('/')
                    wx.navigateToMiniProgram({
                        appId: appId,
                        path: path,
                        success(res) {
                            resolve(res)
                        }
                    })
                } else if (/^applet::/.test(url)) { // 小程序内部路径    链接格式    applet::小程序路径       如 applet::/index/index
                    url = url.split('applet::')[1]

                    if (type === 'redirectTo') {
                        wx.redirectTo({
                            url,
                            success(res) {
                                resolve(res)
                            }
                        })
                    } else {
                        wx.navigateTo({
                            url,
                            success(res) {
                                resolve(res)
                            }
                        })
                    }

                } else if (/^tab::/.test(url)) { // 小程序tab路径     链接格式    tab::小程序路径       如 tab::/index/index
                    url = url.split('tab::')[1]
                    wx.switchTab({
                        url: url,
                        success(res) {
                            resolve(res)
                        }
                    })
                }
                break

            case 1:
                toast('应用建设中')
                break

            case 2:
                toast('应用维护中，请稍后再试')
                break

            case 3:
                toast('应用已下线')
        }
    })

}

export function goAppList(urls) {
    if (urls.length) {
        goApp(urls[0].url, urls[0].type)
        if (urls[0].time) {
            setTimeout(() => {
                urls.splice(0, 1)
                goAppList(urls)
            }, urls[0].time)
        }
    }

}

export function addLog(data) {
    if (global.env === 'release') {
        data.userId = user.userId
        data.userName = user.userName
        wx.request({
            url: 'https://cloudcode.51zidan.com/api/log/',
            data: data,
            method: 'get'
        })
    }
}

/**
 * 扫描周边ibeacon设备
 * @param { Array<String> | Null } beaconIds 如果传则表示指定搜索该设备，不传则表示获取所有设备
 * @param { Boolean | Null } isLoading 是否添加搜索中界面
 */
export function scanfIBeacon(beaconIds = [], isLoading) {
    console.log(beaconIds, 'scanfIBeacon')
    return new Promise((resolve, reject) => {
        wx.startBeaconDiscovery({
            uuids: ['FDA50693-A4E2-4FB1-AFCF-C6EB07647825', '22360679-7749-9789-6964-091736687312']
        }).then(() => {
            console.log('scanf start')
            if (isLoading)
                wx.showLoading({
                    title: '正在搜索',
                    mask: true,
                })
            let timer
            let time = 0
            let beacons = []
            const clear = () => {
                console.log('scanf stop')
                // 清除倒计时
                clearInterval(timer)
                // 停止监听beacon
                wx.offBeaconUpdate()
                wx.stopBeaconDiscovery()
                if (isLoading)
                    wx.hideLoading()
            }

            wx.onBeaconUpdate((res) => {
                console.log(res)
                // res.beacons = res.beacons.filter(item=>item.accuracy < 25) // 限定设备距离
                beacons.push(...res.beacons.map(item => item.major + '' + item.minor))
                console.log(beacons)
            })
            wx.onBeaconServiceChange(res => {
                console.log(res)
                clear()
                reject()
                wx.offBeaconServiceChange()
            })
            if (beaconIds.length) {
                timer = setInterval(() => {
                    time += 1
                    if (time > 3) {
                        beacons.forEach(item => {
                            if (beaconIds.indexOf(item) !== -1) {
                                console.log('找到设备')
                                resolve([item])
                                clear()
                            }
                        })
                    }
                    if (time === 60) {
                        clear()
                        reject('未找到打卡设备')
                    }
                }, 1000)
            } else { // 不搜索指定的beacon时，至少等待5秒才可以返回结果
                timer = setInterval(() => {
                    time += 1
                    if (time > 5 && beacons.length > 0) {
                        resolve(beacons)
                        clear()
                    }
                    if (time === 60) {
                        clear()
                        reject('未找到打卡设备')
                    }
                }, 1000)
            }

        }, (err) => {
            console.log(err)
            switch (err.errCode) {
                case 11000:
                    reject('该设备或系统不支持，请检查微信蓝牙权限')
                    break
                case 11001:
                    reject('蓝牙未打开，请打开蓝牙后重试')
                    break
                case 11002:
                    reject('GPS定位未打开，请打开定位后重试')
                    break
                default:
                    reject('硬件信息读取错误，请稍后再试')
            }
        })
    })
}

export function stopScanfIBeacon() {
    wx.stopBeaconDiscovery()
}


/**
 * 扫描周边ibeacon设备
 */
function ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
            return ('00' + bit.toString(16)).slice(-2)
        }
    )
    return hexArr.join('')
}
export function scanfBluetooth(beaconIds) {
    return new Promise((resolve, reject) => {
        console.log('初始化蓝牙设备')
        wx.openBluetoothAdapter().then(() => {
            const scanf = () => {
                wx.startBluetoothDevicesDiscovery({
                    powerLevel: 'high'
                }).then(() => {
                    const sbuInsert = (str, length) => {
                        let low = str.toUpperCase()
                        let reg = new RegExp('\\w{1,' + length + '}', 'g')
                        let ma = low.match(reg)
                        return ma.join(':')
                    }
                    let timer
                    let time = 0
                    const devices = []
                    wx.onBluetoothDeviceFound(res => {
                        console.log('onBluetoothDeviceFound', res)
                        const list = res.devices.filter(item => {
                            if (item.serviceData && Object.keys(item.serviceData).length) {
                                return true
                            }
                            return false
                        }).map(item => {
                            const key = Object.keys(item.serviceData)[0]
                            const value = ab2hex(item.serviceData[key])
                            console.log(ab2hex(item.serviceData[key]))
                            if (item.name === 'lantun') { // 名称为蓝豚则是自定义打卡设备
                                const data = value.slice(0, 12)
                                return sbuInsert(data, 2)
                            } else if (item.name === 'X-0CEC80FE82A2') { // 兼容腾讯
                                return sbuInsert('0CEC80FE82A2', 2)
                            } else { // 否则解析minor的值
                                const major = parseInt(value.slice(2, 6), 16)
                                const minor = parseInt(value.slice(6, 10), 16)
                                return major + '' + minor
                            }
                        })

                        if (list.length) {
                            devices.push(...list)
                        }
                    })
                    timer = setInterval(() => {
                        time += 1
                        if (beaconIds.length) { // 搜索设备
                            devices.map(item => {
                                if (beaconIds.indexOf(item) !== -1) {
                                    clearInterval(timer)
                                    resolve(devices)
                                    wx.stopBluetoothDevicesDiscovery()
                                    wx.closeBluetoothAdapter()
                                }
                            })
                        } else if (time % 3 === 0 && devices.length) {
                            clearInterval(timer)
                            resolve(devices)
                            wx.stopBluetoothDevicesDiscovery()
                            wx.closeBluetoothAdapter()
                        }
                        if (time === 30) {
                            wx.getBluetoothDevices().then(res => {
                                console.log('getBluetoothDevices', res)
                                const devices = res.devices.filter(item => {
                                    if (item.serviceData && Object.keys(item.serviceData).length) {
                                        return true
                                    }
                                    return false
                                }).map(item => {
                                    const key = Object.keys(item.serviceData)[0]
                                    const value = ab2hex(item.serviceData[key])
                                    console.log(ab2hex(item.serviceData[key]))
                                    if (item.name === 'lantun') { // 名称为蓝豚则是自定义打卡设备
                                        const data = value.slice(0, 12)
                                        return sbuInsert(data, 2)
                                    } else if (item.name === 'X-0CEC80FE82A2') { // 兼容腾讯
                                        return sbuInsert('0CEC80FE82A2', 2)
                                    } else { // 否则解析minor的值
                                        const major = parseInt(value.slice(2, 6), 16)
                                        const minor = parseInt(value.slice(6, 10), 16)
                                        return major + '' + minor
                                    }
                                })
                                if (devices.length) {
                                    resolve(devices)
                                } else {
                                    reject('未找到考勤机')
                                }
                                clearInterval(timer)
                                wx.stopBluetoothDevicesDiscovery()
                                wx.closeBluetoothAdapter()
                            })
                        }
                    }, 1000)
                }, err => {
                    reject(err.errMsg)
                })
            }
            wx.openBluetoothAdapter({
                mode: 'peripheral'
            }).then(res => {
                console.log(res)
                scanf()
            }, err => {
                console.log(err)
                scanf()
            })
        }, err => {
            console.log(err)
            switch (err.errCode) {
                case 10001:
                    reject('未打开蓝牙，请打开蓝牙后再试')
                    break
                case 10009:
                    reject('系统版本过低')
                    break
                default:
                    reject(err.errMsg)
            }
        })
    })
}
export function stopScanfBluetooth() {
    wx.stopBluetoothDevicesDiscovery()
    wx.closeBluetoothAdapter()
}

// 封装方法，对错误进行处理，防止影响主流程
export function reportEvent(name, data) {
    try {
        wx.reportEvent(name, data)
    } catch (e) {
        console.log(e)
    }
}

export function goToContract(flowPath, id) {
    console.log(id, flowPath)
    testContract({
        id: id
    }).then(res => {
        console.log(res, 'res')
        if (res.openBankAddress !== 'true' && res.bankCardNo !== 'true' && res.permanentResidenceAddress !== 'true' && res.emergencyContact !== 'true' && res.emergencyContactAddr !== 'true' && res.emergencyContactPhone !== 'true' && res.nowAddress !== 'true') {
            if (res.idCardFront !== 'true' && res.idCardBack !== 'true') {
                if (res.healthCard !== 'true') {
                    wx.navigateToMiniProgram({
                        appId: 'wxa023b292fd19d41d',
                        path: res.flowPath
                    })
                } else {
                    wx.navigateTo({
                        url: '/pages/health-certificate-info/health-certificate-info',
                    })
                }
            } else {
                wx.navigateTo({
                    url: '/pages/card-info/card-info',
                })
            }
        } else {
            console.log('都等于true')
            wx.navigateTo({
                url: '/pages/contract-info/contract-info?id=' + id,
            })
        }

    })
}

export function getLocation(tips = '小程序将获取您的地理位置信息授权用来获取考勤打卡信息以及提供本地工作与客服服务') {
    return new Promise((resolve, reject) => {
        const fail = () => {
            toast('位置信息授权获取失败，请确认后再试')
            reject()
        }
        wx.getLocation({
            type: 'gcj02',
            success: res => {
                resolve(res)
            },
            fail() {
                wx.showModal({
                    title: '温馨提示',
                    content: tips,
                    success: res => {
                        if (res.confirm) {
                            wx.openSetting({
                                success(res) {
                                    if (res.authSetting['scope.userLocation']) {
                                        getLocation().then(res => {
                                            resolve(res)
                                        }, () => {
                                            fail()
                                        })
                                    } else {
                                        fail()
                                    }
                                },
                                fail() {
                                    fail()
                                }
                            })
                        }
                    },
                    fail() {
                        fail()
                    }
                })
            }
        })
    })
}

/**
 * wait等待
 * @param {number} timeout
 * @returns
 */
export function wait(timeout = 1000) {
    return new Promise(resolve => {
        setTimeout(resolve, timeout)
    })
}


export default {
    confirm,
    alert,
    toast,
    shake,
    wait
}